package site.jlopen.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import site.jlopen.assets.config.ThreadAuthUser;
import site.jlopen.assets.shiro.token.SessionToken;
import site.jlopen.entity.BaseResponse;
import site.jlopen.entity.vo.LoginRes;
import site.jlopen.service.intf.user.UserService;

@Controller
public class LoginController {
	private final Logger log = LoggerFactory.getLogger(getClass());

	@Autowired private UserService userService;
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public BaseResponse<LoginRes> sublogin(Model model, 
			ServletRequest shiroRequest,
			@RequestParam(name = "username") String username,
			@RequestParam(name = "password") String password, 
			HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username, password, true));
            // 设置session失效时间：永不超时
            subject.getSession().setTimeout(-1001);
            LoginRes user = (LoginRes) subject.getSession().getAttribute(ThreadAuthUser.USER_SESSION);
            user.setPassword(null);
			SavedRequest savedRequest = WebUtils.getSavedRequest(shiroRequest);
			if(null != savedRequest && !"".equals(savedRequest.getRequestUrl())) {
				user.setRedirect(savedRequest.getRequestUrl());
			}
			return new BaseResponse<LoginRes>().success("登录成功").setData(user);
        } catch (UnknownAccountException e) {
			return new BaseResponse<LoginRes>().error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
			return new BaseResponse<LoginRes>().error("用户名或密码错误！");
        }
	}
	
	@RequestMapping(value = "/logon", method = RequestMethod.POST)
	public String sublogon(Model model, 
			ServletRequest shiroRequest,
			@RequestParam(name = "username") String username,
			@RequestParam(name = "password") String password, 
			HttpServletRequest request) {
		if("".equals(username) || null == username) {
			model.addAttribute("error", "请输入账号");
		}
		if("".equals(password) || null == password) {
			model.addAttribute("error", "请输入密码");
		}
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(username, password, false));
            SavedRequest savedRequest = WebUtils.getSavedRequest(shiroRequest);
			if(null != savedRequest && !"".equals(savedRequest.getRequestUrl())) {
	            return "redirect:/" + savedRequest.getRequestUrl();
			}
            return "redirect:/index";
        } catch (UnknownAccountException e) {
			model.addAttribute("error", "账号/密码错误");
        } catch (IncorrectCredentialsException e) {
			model.addAttribute("error", "账号/密码错误");
        }
		return "login";
	}
	
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ResponseBody
	public BaseResponse<String> subregister(
			@RequestParam(name = "username") String username,
			@RequestParam(name = "password") String password) {
		return userService.register(username, password);
	}
}
